<template>
  <div class="app-container">
    <el-button type="primary" @click="addDetail">添加</el-button>
    <el-table :data="dataList" style="width: 100%;margin-top: 30px;" v-loading.body="listLoading" border>
      <el-table-column align="center" label="序号" width="100">
        <template scope="scope">
          {{scope.row.index}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="品类名称" width="200">
        <template scope="scope">
          {{getCategoryLabel(scope.row.categoryId)}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="性别" width="200">
        <template scope="scope">
          {{scope.row.sex==0?'男士':'女士'}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="类型名称" width="200">
        <template scope="scope">
          {{scope.row.detailName}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="类型图片" width="200">
        <template scope="scope">
          <img :src="scope.row.detailImage" min-width="120" height="120" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="排序" width="200">
        <template scope="scope">
          {{scope.row.orderNum}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300">
        <template scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
    </div>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑详情':'添加详情'">
      <el-form autoComplete="on" :model="item" label-width="80px" label-position="left" ref="detail" :rules="rules">

        <el-form-item label="品类" prop="categoryId">
          <el-select class="el-input" v-model="item.categoryId" placeholder="请选择">
            <el-option v-for="it in categoryArray" :key="it.value" :label="it.label" :value="it.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="名称" prop="detailName">
          <el-input autoComplete="on" name="detailName" v-model="item.detailName" placeholder="品类名称"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-select class="el-input" v-model="item.sex" placeholder="请选择">
            <el-option v-for="it in sexes" :key="it.value" :label="it.label" :value="it.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="图片">
          <el-upload class="avatar-uploader" action="/api/shop/file/upload" :show-file-list="false"
            :on-success="uploadSuccess" :before-upload="beforeUpload" :headers="getToken()" :onError="uploadError">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>

        </el-form-item>

        <el-form-item label="排序" prop="orderNum">
          <el-input autoComplete="on" name="orderNum" v-model="item.orderNum" placeholder="排序"></el-input>
        </el-form-item>

      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmAdd">确认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  const detail = {
    id: '',
    categoryId: '',
    detailName: '',
    sex: '',
    detailImage: '',
    status: 0,
    orderNum: 0
  }
  import { all } from 'api/shopCagegory'
  import { token, save, page } from 'api/shopCategoryDetail'
  import { client } from '../../../utils/oss.js'
  export default {
    data() {
      return {
        item: Object.assign({}, detail),
        categoryArray: [],
        dialogVisible: false,
        dialogType: 'new',
        listLoading: false,
        checkStrictly: false,
        total: 10,
        dataList: [],
        imageUrl: undefined,

        defaultProps: {
          children: 'children',
          label: 'title'
        },
        listQuery: {
          page: 1,
          limit: 20,
          name: undefined
        },
        sexes: [{
          value: '0',
          label: '男士'
        }, {
          value: '1',
          label: '女士'
        }],
        rules: {
          categoryId: [{
            required: true,
            message: '请选择品类',
            trigger: 'blur'
          }],
          detailName: [{
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }],
          sex: [{
            required: true,
            message: '请选择性别',
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      this.getCategory()
      this.getlist()
    },
    methods: {
      getlist() {
        this.listLoading = true
        page(this.listQuery).then(response => {
          var data = response.data
          this.dataList = data.rows;
          this.total = data.total;
          this.listLoading = false;
          for (var ix in this.dataList) {
            this.dataList[ix].index = parseInt(ix, 10) + 1;
          }
          console.log(this.dataList)
          this.listLoading = false
        })
      },
      handleEdit(scope) {
        var data = this.dataList[scope.row.index - 1]
        this.item.detailName = data.detailName
        this.item.categoryId = data.categoryId
        this.item.sex = data.sex
        this.item.orderNum = data.orderNum
        this.item.id = data.id
        this.item.status = 1
        this.dialogType = 'edit'
        this.dialogVisible = true
      },
      getCategory() {
        var that = this
        all().then((res) => {
          if (res.status == 200) {
            for (var ix in res.data) {
              that.categoryArray.push({ "value": res.data[ix].id, "label": res.data[ix].name })
            }
          }
          console.log(res)
        })
      },
      getCategoryLabel(value) {
        for (var ix in this.categoryArray) {
          if (this.categoryArray[ix].value == value) {
            return this.categoryArray[ix].label
          }
        }
      },
      addDetail() {

        this.dialogType = 'new'
        this.dialogVisible = true
        this.item = Object.assign({}, detail);
        this.item.id = ''
        this.item.categoryId = ''
        this.item.sex = ''
        this.item.detailName = ''
        this.item.detailImage = ''
        this.item.status = 1
      },
      beforeUpload(file) {
        //let fd = new Formdata()
        //fd.append('key', file.raw, 'fileName')
        // todo
      },
      // 上传成功后的回调
      uploadSuccess(response, file, fileList) {
        if (response.status == 200) {
          this.imageUrl = 'http://localhost:9762/api/shop/file/image/' + response.data
        } else {
          this.$error('上传失败')
        }
      },
      // 上传错误
      uploadError(response, file, fileList) {
        console.log('上传失败，请重试！')
      },
      getToken() {
        var data = { 'token': token().token }
        return data
      },
      //上传到阿里云
      async fnUploadRequest(file) {
        const self = this
        let files = file.file,
          point = files.name.lastIndexOf('.'),
          suffix = files.name.substr(point),
          fileName = files.name.substr(0, point),
          date = Date.parse(new Date()),
          fileNames = `${fileName}_${date}${suffix}`;

        //fileNames上传文件的名称
        //file.file上传文件的内容
        client().put(fileNames, file.file).then(result => {
          //下面是如果对返回结果再进行处理，根据项目需要
          console.log(result)
          self.$message({
            message: '上传成功',
            type: 'success'
          });
        }).catch(err => {
          self.$message.error('上传失败');
        })
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
      },
      confirmAdd() {
        this.$refs.detail.validate(valid => {
          this.item.detailImage = this.imageUrl
          save(this.item).then(res => {
            if (res.status == 200) {
              this.dialogType = 'edit'
              this.dialogVisible = false
              this.$success('保存成功')
              this.getlist()
            } else {
              this.$error('保存失败')
            }
          })
        })

      }
    },
  }
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>